package com.dd.stack.es.service.internal;

import com.dd.stack.es.pojo.es.EcommerceProductESDO;
import com.dd.stack.es.pojo.req.complex.ProductQueryReq;
import lombok.RequiredArgsConstructor;
import org.apache.lucene.search.join.ScoreMode;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.elasticsearch.index.query.*;
import org.springframework.data.elasticsearch.core.*;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/4/20 1:42
 * @Description EcommerceProductService
 */
@Service
@RequiredArgsConstructor
public class EcommerceProductService {

    private final ElasticsearchOperations elasticsearchOperations;

    public PageImpl<EcommerceProductESDO> searchProducts(ProductQueryReq queryReq) {
        // 构建BoolQuery (组合多个查询条件)
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 添加基本字段查询条件
        addBasicFieldQueries(boolQuery, queryReq);
        // 添加嵌套对象查询条件
        addNestedFieldQueries(boolQuery, queryReq);
        // 构建NativeSearchQuery
        Pageable pageable = PageRequest.of(
                queryReq.getPageParams().getPageNum() - 1,
                queryReq.getPageParams().getPageSize()
        );
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(boolQuery)
                .withPageable(pageable);
        // 添加排序
        //if (StringUtils.hasText(queryReq.getSort())) {
        //    String[] sortParams = queryReq.getSort().split(",");
        //    if (sortParams.length == 2) {
        //        queryBuilder.withSort(SortBuilders.fieldSort(sortParams[0])
        //                .order(SortOrder.fromString(sortParams[1])));
        //    }
        //}

        NativeSearchQuery query = queryBuilder.build();

        SearchHits<EcommerceProductESDO> searchHits = elasticsearchOperations.search(query, EcommerceProductESDO.class);

        // 转换为分页结果
        List<EcommerceProductESDO> pdts = searchHits.stream()
                .map(SearchHit::getContent)
                .collect(Collectors.toList());

        return new PageImpl<>(
                pdts,
                pageable,
                searchHits.getTotalHits()
        );
    }

    private void addBasicFieldQueries(BoolQueryBuilder boolQuery, ProductQueryReq queryReq) {
        // 产品ID精确匹配
        if (StringUtils.hasText(queryReq.getProductId())) {
            boolQuery.must(QueryBuilders.termQuery("productId", queryReq.getProductId()));
        }

        // 名称模糊查询
        if (StringUtils.hasText(queryReq.getName())) {
            boolQuery.must(QueryBuilders.matchQuery("name", queryReq.getName())
                    .boost(2.0f));
        }

        // 描述全文检索
        if (StringUtils.hasText(queryReq.getDescription())) {
            boolQuery.must(QueryBuilders.matchQuery("description", queryReq.getDescription()));
        }

        // 价格范围查询
        if (queryReq.getPriceRange() != null) {
            RangeQueryBuilder priceQuery = QueryBuilders.rangeQuery("price");
            if (queryReq.getPriceRange().getMin() != null) {
                priceQuery.gte(queryReq.getPriceRange().getMin().doubleValue());
            }
            if (queryReq.getPriceRange().getMax() != null) {
                priceQuery.lte(queryReq.getPriceRange().getMax().doubleValue());
            }
            boolQuery.must(priceQuery);
        }

        // 其他基本字段条件...
    }

    private void addNestedFieldQueries(BoolQueryBuilder boolQuery, ProductQueryReq queryReq) {
        // 分类查询(AND关系)
        if (!CollectionUtils.isEmpty(queryReq.getCategories())) {
            BoolQueryBuilder categoryQuery = QueryBuilders.boolQuery();
            queryReq.getCategories().forEach(category ->
                    categoryQuery.must(QueryBuilders.termQuery("categories", category)));
            boolQuery.must(categoryQuery);
        }

        // 标签查询(OR关系)
        if (!CollectionUtils.isEmpty(queryReq.getTags())) {
            BoolQueryBuilder tagQuery = QueryBuilders.boolQuery();
            queryReq.getTags().forEach(tag ->
                    tagQuery.should(QueryBuilders.termQuery("tags.keyword", tag)));
            boolQuery.must(tagQuery.minimumShouldMatch(1));
        }

        // 属性嵌套查询
        if (!CollectionUtils.isEmpty(queryReq.getAttributes())) {
            queryReq.getAttributes().forEach(attr -> {
                BoolQueryBuilder attrQuery = QueryBuilders.boolQuery();
                if (StringUtils.hasText(attr.getName())) {
                    attrQuery.must(QueryBuilders.termQuery("attributes.name", attr.getName()));
                }
                if (StringUtils.hasText(attr.getValue())) {
                    attrQuery.must(QueryBuilders.matchQuery("attributes.value", attr.getValue()));
                }
                if (attr.getIsVisible() != null) {
                    attrQuery.must(QueryBuilders.termQuery("attributes.is_visible", attr.getIsVisible()));
                }

                boolQuery.must(QueryBuilders.nestedQuery("attributes", attrQuery, ScoreMode.None));
            });
        }

        // 其他嵌套字段查询...
    }
}